package com.whmnx.my.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.whmnx.base.utils.PhotoUtil;
import com.whmnx.my.BR;
import com.whmnx.my.R;
import com.whmnx.my.databinding.FragmentRenZhengBinding;
import com.whmnx.my.ui.viewmodel.RenModel;

import java.io.File;

import me.goldze.mvvmhabit.base.BaseActivity;

import static com.whmnx.my.ui.viewmodel.EidtModel.CODE_CAMERA_REQUEST;
import static com.whmnx.my.ui.viewmodel.RenModel.REQUEST_CODE_CAMERA;

/**
 * author : huang
 * date   : 2020/9/29 0029 9:27
 * version: 1.0
 * @author Administrator
 */
public class MyRenZhengFragment extends BaseActivity<FragmentRenZhengBinding, RenModel> {

    public int index = 0;
    public String name = "";
    String sex = "";
    String nation = "";
    public  String num = "";
    String address = "";
    private int type;

    public String filePath2;
    public boolean flag;
    public boolean flag2;
    public String filePath1;
    public Uri cropImageUri;
    public Uri imageUri;
    public File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");

    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    public boolean flag3;


    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.initToolbar(this,binding);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化
        initAccessTokenWithAkSk();
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.fragment_ren_zheng;
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                Log.i("wyb", "token is " + token);
                // 本地自动识别需要初始化
                initLicense();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                ToastUtil.toastShortMessage("AK，SK方式获取token失败");
            }
        }, getApplicationContext(), "8YEROg4CqtfsIHdnBdU8vTHd", "kKirORxuPDs7fIkIsxetCF2oPZ7aAKTP");
    }

    private void initLicense() {
        CameraNativeHelper.init(this, OCR.getInstance(this).getLicense(),
                (errorCode, e) -> {
                    final String msg;
                    switch (errorCode) {
                        case CameraView.NATIVE_SOLOAD_FAIL:
                            msg = "加载so失败，请确保apk中存在ui部分的so";
                            break;
                        case CameraView.NATIVE_AUTH_FAIL:
                            msg = "授权本地质量控制token获取失败";
                            break;
                        case CameraView.NATIVE_INIT_FAIL:
                            msg = "本地质量控制";
                            break;
                        default:
                            msg = String.valueOf(errorCode);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = getFile(index).getAbsolutePath();
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                    index++;
                }
            }
        }else if (requestCode == CODE_CAMERA_REQUEST){
            flag3 = true;
            cropImageUri = Uri.fromFile(fileUri);
           // PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
            Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
            if (bitmap != null) {
                binding.ivCode3.setImageBitmap(bitmap);
            }
        }
    }

    private void recIDCard(String idCardSideFront, String filePath) {
        IDCardParams param = new IDCardParams();
        // 设置身份证正反面
        param.setIdCardSide(idCardSideFront);
        param.setImageFile(new File(filePath));
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(40);

        OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult idCardResult) {
                if (idCardResult != null) {
                    if (idCardSideFront.equals("front")) {

                        if (idCardResult.getName() != null) {
                            name = idCardResult.getName().toString();
                            binding.etName.setText(name);
                        }
                        if (idCardResult.getGender() != null) {
                            sex = idCardResult.getGender().toString();
                        }
                        if (idCardResult.getEthnic() != null) {
                            nation = idCardResult.getEthnic().toString();
                        }
                        if (idCardResult.getIdNumber() != null) {
                            num = idCardResult.getIdNumber().toString();
                            binding.etCode.setText(num);
                        }
                        if (idCardResult.getAddress() != null) {
                            address = idCardResult.getAddress().toString();
                        }

                        if (!TextUtils.isEmpty(num)) {
                            flag = true;
                            binding.ivCode.setImageURI(Uri.fromFile(new File(filePath)));
                            filePath2 = filePath;
                        }
                    } else {
                        String issueAuthority = "";
                        String expiryDate = "";
                        if (idCardResult.getIssueAuthority() != null) {
                            issueAuthority = idCardResult.getIssueAuthority().toString();
                        }
                        if (idCardResult.getExpiryDate() != null) {
                            expiryDate = idCardResult.getExpiryDate().toString();
                        }
                        if (!TextUtils.isEmpty(issueAuthority)) {
                            flag2 = true;
                            binding.ivCode2.setImageURI(Uri.fromFile(new File(filePath)));
                            filePath1 = filePath;
                          //  list_path.add(filePath1);
                        }
                    }
                } else {
                    ToastUtil.toastShortMessage("扫描身份证失败,请重新扫描");
                }
            }

            @Override
            public void onError(OCRError ocrError) {
                ocrError.printStackTrace();
                ToastUtil.toastShortMessage("扫描身份证失败");
            }
        });
    }

    public File getFile(int i) {
        return new File(getFilesDir(), i + "pic.jpg");
    }
}
